package com.nitty.cash.loop.ui.fragment

import android.graphics.Color
import android.view.LayoutInflater
import android.view.View
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.nitty.cash.loop.R
import com.nitty.cash.loop.common.CommonFragment
import com.nitty.cash.loop.configs.NittyApiPath
import com.nitty.cash.loop.configs.NittyApiUrl
import com.nitty.cash.loop.configs.NittyApiUrl.addCommonParams
import com.nitty.cash.loop.databinding.UiPageTabMessageBinding
import com.nitty.cash.loop.event.NittyEventData
import com.nitty.cash.loop.event.NittyEventPointType
import com.nitty.cash.loop.request.IHttpCallback
import com.nitty.cash.loop.ui.activity.ProcessAct
import com.nitty.cash.loop.ui.adapter.MessageAdapter
import com.nitty.cash.loop.utils.helper.NittyProcessHelper
import com.nitty.cash.loop.utils.helper.TestDataLibInvoke
import org.json.JSONObject

/**
 * NittyCash
 * @Author wwdeng
 * @CreateTime: 2024/12/10 14:53
 * @Annotation：消息
 */
class TabMessageFragment: CommonFragment() {
    lateinit var binding: UiPageTabMessageBinding
    private var messageAdapter: MessageAdapter? = null

    override fun getNittyRootView(inflater: LayoutInflater): View {
        binding = UiPageTabMessageBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun initNittyView() {
        setNittyRootParentBackgroundColor(Color.parseColor("#FFF5F5F5"))
        setNittyTitleBarVisibility(View.VISIBLE)
        setNittyTitleBarColor(Color.parseColor("#FFFFFFFF"))
        setNittyBackBtnVisibility(View.GONE)
        setNittyTextTitle(getString(R.string.nitty_main_tab3_title))
        setNittyRightBtnRes(R.mipmap.img_customer_black)

        initMessageRefrashView()
        initMessageRecyclerView()
    }

    override fun initNittyListener() {
        rootViewBinding.rootCustomer.setOnClickListener {
            showCustomerDialog("Message Page")
            addEventPointRequestAction(NittyEventPointType.CLICK.NITTY_CLICK_CUSTOMER,"Message Page")
        }
    }

    override fun loadNittyData() {
        addEventPointRequestAction(NittyEventPointType.PAGE.NITTY_PAGE_MESSAGE_START)
        showNittyLoading()
        getNittyMessageListAction()
    }

    /* 初始化刷新 */
    private fun initMessageRefrashView() {
        binding.messageRefreshLayout.setColorSchemeResources(R.color.theme,R.color.purple_500)
        binding.messageRefreshLayout.setOnRefreshListener {
            getNittyMessageListAction()
        }
    }

    /**
     * 初始化Views
     */
    private fun initMessageRecyclerView(){
        val layoutManager = LinearLayoutManager(requireContext())
        layoutManager.orientation = RecyclerView.VERTICAL
        binding.rvMessge.layoutManager = layoutManager
        messageAdapter = MessageAdapter(binding.rvMessge)
        binding.rvMessge.adapter = messageAdapter!!
        binding.rvMessge.itemAnimator = DefaultItemAnimator()
        messageAdapter?.setOnItemChildClickListener { _, childView, position ->
            val item = messageAdapter!!.getItem(position)
            when(item.optString("type")){
                "REPAY_REMIDER",//还款提醒
                "APPLY_STATUS_UPDATE" -> {//申请状态更新
                    publishEventData(NittyEventData(NittyEventData.TYPE.NITTY_SHOW_REPAY))
                }
                else -> {//AD_MESSAGE  广告推广
                    if (NittyProcessHelper.getAuthProcessList().size == 0) {//流程已完成 - 进入首页
                        //进入还款页
                        publishEventData(NittyEventData(NittyEventData.TYPE.NITTY_SHOW_REPAY))
                    } else {
                        //流程未完成 - 进入流程页面
                        //上报
                        TestDataLibInvoke.sycData()
                        onIntent(ProcessAct::class.java)
                    }
                }
            }
        }
    }

    /**
     * 设置消息列表
     */
    private fun setNittyMessageList(messageList: ArrayList<JSONObject>){
        if (messageList.size == 0){
            messageAdapter?.clear()
            val emptyItem = JSONObject()
            emptyItem.put("isEmptyView",true)
            messageAdapter?.addFirstItem(emptyItem)
            return
        }
        messageAdapter?.data = messageList
    }

    private fun getNittyMessageListAction(){
        val httpUrl = NittyApiUrl.getHttpUrl()
        val params = JSONObject().addCommonParams().apply {
            put("xd304965bcd9478080", NittyApiPath.NITTY_PATH.NITTY_API_MESSAGE_LIST_PATH)
        }
        doPostAction(httpUrl,params,object : IHttpCallback {
            override fun onRequestSuccess(data: JSONObject) {
                when(data.optInt("code")){
                    0 -> {
                        val array = data.optJSONArray("obj")
                        if (array != null){
                            val list = arrayListOf<JSONObject>()
                            for (i in 0..<array.length()){
                                val item = array.optJSONObject(i)
                                list.add(item)
                            }
                            setNittyMessageList(list)
                        }
                    }
                    else -> {
                        val msg = data.optString("msg")
                        showNittyToast(msg)
                    }
                }
            }

            override fun onRequestError(error: JSONObject) {
                showNittyToast(error.optString("errorMsg"))
            }

            override fun onRequestFinish() {
                hiddenNittyLoading()
            }
        })
    }

    override fun hiddenNittyLoading() {
        super.hiddenNittyLoading()
        binding.messageRefreshLayout.isRefreshing = false
    }

    override fun onDestroy() {
        super.onDestroy()
        addEventPointRequestAction(NittyEventPointType.PAGE.NITTY_PAGE_MESSAGE_END)
    }
}